package com.xyy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyy.entity.Activity;
import com.xyy.entity.Doctor;
import com.xyy.entity.DoctorActivityRegistration;
import com.xyy.entity.DoctorActivityRegistrationVO;
import com.xyy.exception.BusinessException;
import com.xyy.mapper.ActivityMapper;
import com.xyy.mapper.DoctorActivityRegistrationMapper;
import com.xyy.mapper.DoctorMapper;
import com.xyy.service.DoctorActivityRegistrationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * 医生活动报名服务实现类
 */
@Service
public class DoctorActivityRegistrationServiceImpl 
    extends ServiceImpl<DoctorActivityRegistrationMapper, DoctorActivityRegistration> 
    implements DoctorActivityRegistrationService {
    
    @Autowired
    private DoctorActivityRegistrationMapper doctorActivityRegistrationMapper;
    
    @Autowired
    private DoctorMapper doctorMapper;
    
    @Autowired
    private ActivityMapper activityMapper;
    
    @Override
    public IPage<Activity> getAvailableActivitiesForDoctor(Long doctorId, Long current, Long size) {
        IPage<Activity> page = new Page<>(current, size);
        return doctorActivityRegistrationMapper.selectAvailableActivitiesForDoctor(page, doctorId);
    }
    
    @Override
    public IPage<Activity> getRegisteredActivitiesByDoctor(Long doctorId, Long current, Long size) {
        IPage<Activity> page = new Page<>(current, size);
        return doctorActivityRegistrationMapper.selectRegisteredActivitiesByDoctor(page, doctorId);
    }
    
    @Override
    public IPage<com.xyy.vo.DoctorActivityVO> getRegisteredActivitiesWithStatusByDoctor(Long doctorId, Long current, Long size) {
        IPage<com.xyy.vo.DoctorActivityVO> page = new Page<>(current, size);
        return doctorActivityRegistrationMapper.selectRegisteredActivitiesWithStatusByDoctor(page, doctorId);
    }
    
    @Override
    @Transactional
    public boolean registerActivity(Long activityId, Long doctorId, String remark) {
        // 检查是否已经报名
        DoctorActivityRegistration existing = doctorActivityRegistrationMapper
            .selectByActivityAndDoctor(activityId, doctorId);
        if (existing != null) {
            throw new BusinessException("您已经报名过此活动");
        }
        
        // 创建报名记录
        DoctorActivityRegistration registration = new DoctorActivityRegistration();
        registration.setActivityId(activityId);
        registration.setDoctorId(doctorId);
        registration.setStatus("REGISTERED");
        registration.setRegistrationTime(LocalDateTime.now());
        registration.setRemark(remark);
        registration.setPointsEarned(0);
        
        return this.save(registration);
    }
    
    @Override
    @Transactional
    public boolean cancelRegistration(Long activityId, Long doctorId) {
        LambdaQueryWrapper<DoctorActivityRegistration> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DoctorActivityRegistration::getActivityId, activityId)
                    .eq(DoctorActivityRegistration::getDoctorId, doctorId);
        
        return this.remove(queryWrapper);
    }
    
    @Override
    public Integer countAttendedActivitiesByDoctor(Long doctorId) {
        return doctorActivityRegistrationMapper.countAttendedActivitiesByDoctor(doctorId);
    }
    
    @Override
    public Integer getTotalPointsByDoctor(Long doctorId) {
        Integer points = doctorActivityRegistrationMapper.sumPointsByDoctor(doctorId);
        return points != null ? points : 0;
    }
    
    @Override
    @Transactional
    public boolean approveRegistrationAndGivePoints(Long registrationId, String status, Integer pointsEarned) {
        // 获取报名记录
        DoctorActivityRegistration registration = this.getById(registrationId);
        if (registration == null) {
            throw new BusinessException("报名记录不存在");
        }
        
        // 如果没有指定积分，使用活动设置的默认积分
        if (pointsEarned == null || pointsEarned <= 0) {
            // 获取活动信息
            Activity activity = activityMapper.selectById(registration.getActivityId());
            if (activity != null && activity.getPoints() != null && activity.getPoints() > 0) {
                pointsEarned = activity.getPoints();
            } else {
                pointsEarned = 0;
            }
        }
        
        // 更新报名状态和积分
        LambdaUpdateWrapper<DoctorActivityRegistration> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(DoctorActivityRegistration::getId, registrationId)
                    .set(DoctorActivityRegistration::getStatus, status)
                    .set(DoctorActivityRegistration::getPointsEarned, pointsEarned);
        
        if ("COMPLETED".equals(status)) {
            updateWrapper.set(DoctorActivityRegistration::getCompleteTime, LocalDateTime.now());
        }
        
        boolean updateResult = this.update(updateWrapper);
        
        if (updateResult && pointsEarned != null && pointsEarned > 0) {
            // 更新医生总积分
            Doctor doctor = doctorMapper.selectById(registration.getDoctorId());
            if (doctor != null) {
                Integer currentPoints = doctor.getPoints() != null ? doctor.getPoints() : 0;
                doctor.setPoints(currentPoints + pointsEarned);
                doctorMapper.updateById(doctor);
            }
        }
        
        return updateResult;
    }
    
    @Override
    public IPage<DoctorActivityRegistration> getRegistrationsByActivity(Long activityId, Long current, Long size) {
        IPage<DoctorActivityRegistration> page = new Page<>(current, size);
        return doctorActivityRegistrationMapper.selectRegistrationsByActivity(page, activityId);
    }
    
    @Override
    public IPage<DoctorActivityRegistrationVO> getRegistrationsByActivityWithDoctorInfo(Long activityId, Long current, Long size) {
        IPage<DoctorActivityRegistrationVO> page = new Page<>(current, size);
        return doctorActivityRegistrationMapper.selectRegistrationsByActivityWithDoctorInfo(page, activityId);
    }
    
    @Override
    public Integer countTodayActivitiesByDoctor(Long doctorId) {
        return doctorActivityRegistrationMapper.countTodayActivitiesByDoctor(doctorId);
    }
    
    @Override
    public Integer countThisMonthActivitiesByDoctor(Long doctorId) {
        return doctorActivityRegistrationMapper.countThisMonthActivitiesByDoctor(doctorId);
    }
    
    @Override
    public Integer countTotalActivitiesByDoctor(Long doctorId) {
        return doctorActivityRegistrationMapper.countTotalActivitiesByDoctor(doctorId);
    }
    
    @Override
    public Integer countAllActivitiesByHospital(Long doctorId) {
        return doctorActivityRegistrationMapper.countAllActivitiesByHospital(doctorId);
    }
}
